<template>
  <div class="picking zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t('安装位置') }}</p>
            <div class="ipt">
              <Cascader
                  :data="orgList"
                  :transfer="true"
                  v-model="orgCode"
                  change-on-select
                  @on-change="handleCasChange"
              />
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('equipCheck.SerialNo') }}</p>
            <div class="ipt">
<!--              <Input type="text"-->
<!--                     v-model="searchParams.deviceName"-->
<!--                     :placeholder="`${$t('common.inputInfo')}`"/>-->
              <Select v-model="searchParams.deviceMId" filterable clearable
                      :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`"
                      :remote-method="handleRemote"
                      @on-clear="clearChange"
                      @on-select="handleChangeWl">
                <Option v-for="item in deviceMIdList"
                        :value="item.deviceMId"
                        :label="item.desc"
                        :key="item.deviceMId"/>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('保养级别') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.itemLevel" clearable
                      :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="item of levelList"
                        :value="item.key"
                        :key="item.key"
                        :label="item.name">
                </Option>
              </Select>
            </div>
          </div>
        </Col>

        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn"
                      type="primary"
                      v-has="'calenderSearch'"
                      @click="serachClick">
                {{ $t('common.Query') }}
              </Button>
              <Button v-has="'calenderSearch'" @click="chongClick" class="reset-btn">{{ $t('common.reset') }}</Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
<!--      <div class="btns clear">-->
<!--        <span class="title">{{ $t('common.listInformation') }}</span>-->
<!--      </div>-->
      <div class="tableContentBox">
        <a-calendar
            v-model="calendarValue"
            :header-render="headerRender"
                    @panelChange="panelChange"
                    @change="dateChange"
                    @select="dateSelect"
                    >
          <div class="dayBox" slot="dateCellRender" slot-scope="value" >
              <div class="oncontextmenuPop" :data-date="$moment(value).format('YYYY-MM-DD HH:mm:ss')">
                  <Tag color="success" @click.native="setDay(value,1)">{{$t('工作日')}}</Tag><br/>
                  <Tag color="error" @click.native="setDay(value,0)">{{$t('非工作日')}}</Tag>
              </div>
              <div class="rightBtns" v-if="searchParams.orgId">
                  <div style="display: inline-block" v-if="workList">
                      <Tag v-if="(workList[$moment(value).format('YYYY-MM-DD')] || {}).isWorkDate===1" color="success" >
                          {{$t('工作日')}}
                      </Tag>
                      <Tag v-if="(workList[$moment(value).format('YYYY-MM-DD')] || {}).isWorkDate===0" color="error" >
                          {{$t('非工作日')}}
                      </Tag>
                  </div>
                  <div style="display: inline-block;vertical-align: middle;" @mousedown="(e)=>{onmousedown(e,$moment(value).format('YYYY-MM-DD HH:mm:ss'))}" class="oncontextmenu iconfont zy-common-shezhi" :data-item="JSON.stringify(value)">
                  </div>
              </div>
            <template v-for="item in getListData(value,'day')">

              <div class="dayBox_item" :key="item" @click="dayitemClick(item)" >

                  <Badge v-if="Number(item.split('@')[2]) !== -1" :color="colorList[item.split('@')[2] == 0 ? 0 :(item.split('@')[2] == 3 || item.split('@')[2] == 4) ? 1 : 2]" />
                <template>
                  <template v-if="Number(item.split('@')[2]) === -1">
                    {{item.split('@')[1].replace(item.split('@')[1].substring(item.split('@')[1].indexOf('('),item.split('@')[1].indexOf(')') + 1), '') + '次'}}
                  </template>
                  <template v-else>
                    {{item.split('@')[1].replace(item.split('@')[1].substring(item.split('@')[1].indexOf('('),item.split('@')[1].indexOf(')') + 1), '') + '-' + statusList[item.split('@')[2] == 0 ? 0 :(item.split('@')[2] == 3 || item.split('@')[2] == 4) ? 1 : 2]}}
                  </template>
                </template>
                <Icon v-if="Number(item.split('@')[2]) !== -1" type="ios-heart" :color="colorList[item.split('@')[2] == 0 ? 0 :(item.split('@')[2] == 3 || item.split('@')[2] == 4) ? 1 : 2]"/>
              </div>
            </template>
          </div>
          <div class="dayBox" slot="monthCellRender" slot-scope="value">
            <template v-for="item in getListData(value,'month')">
              <div class="dayBox_item" :key="item">
                <Tooltip :content="item" placement="top">
                  {{item}}
                </Tooltip>
              </div>
            </template>
          </div>
        </a-calendar>
      </div>
    </div>
  </div>
</template>

<script>
import {findOrgByToken,getMaintenanceMonth,getMaintenanceYear} from "@/api/index.js";
import recursion from "@/util/recursion";
import { Calendar,Radio, Select, Col, Row,Space} from 'ant-design-vue';
import moment from 'moment'
import 'moment/locale/zh-cn';
import {mapGetters} from "vuex";
import fileDownload from "js-file-download";
const RadioGroup = Radio.Group
const selectOption = Select.Option
const radioButton = Radio.Button
export default {
  name: 'index',
  components: {
    ACalendar:Calendar,
    ARadioGroup:RadioGroup,
    ARadioButton:radioButton,
    ASelect:Select,
    ASelectOption:selectOption,
    ARow:Row,
    ACol:Col,
    ASpace:Space,
  },
  computed: {
    ...mapGetters([
      'calendarDeviceId'
    ])
  },
  data() {
    return {
      levelList: [
        {name: "一级保养", key: 1},
        {name: "二级保养", key: 2},
        {name: "三级保养", key: 3},
      ],
      orgCode:[],
      colorList:['gray','green','red'],
      statusList:[
        `${this.$t('未开始')}`,
        `${this.$t('已完成')}`,
        `${this.$t('未完成')}`
      ],
      onTypeChange:null,
      yearMonthstaus:false,
      calendarValue:moment(new Date()),
      dateInfo: moment().format("YYYY年MM月DD日"),
      orgList: [],
      activType:"",
      modeType:"",
      deviceMIdList:[],
      monthList:[],
      dayList:[],
      searchParams:{},
      workList:{}
    }
  },
  beforeCreate(){
    if (localStorage.getItem('language') === 'zh_CN'){
        moment.locale('zh-cn');
    }
  },
  created(){
    if (this.calendarDeviceId){
      this.searchParams.deviceMId = this.calendarDeviceId
      this.handleRemote(this.calendarDeviceId)
    }
  },
  mounted() {
      this.getOrgList()
      this.getMaintenanceMonth()
      let self = this;
      document.oncontextmenu = function (e) {
         self.toggleAllPop('clear')
         if (e.target.className.indexOf('oncontextmenu') > -1)
            return false
          else
             return  true
      }
  },
  methods: {
      getWorkDay(){
          const year = this.dateInfo.slice(0,this.dateInfo.indexOf('年'))
          const month = parseInt(this.dateInfo.slice(this.dateInfo.indexOf('年') + 1,this.dateInfo.indexOf('月')))
          this.axios({
              method: "get",
              url: "/dms/calendar/board/list_work_date",
              params: {
                  year,
                  month,
                  orgId:this.searchParams.orgId,
              },
          }).then((res) => {
              if (res.code === 200) {
                  let data =  res.data;
                  for (let i=0;i<data.length;i++){
                      this.workList[data[i].date] = data[i]
                  }
              } else {
                  this.$Message.warning({
                      content: res.msg,
                      duration: 6,
                      closable: true,
                  });
              }
          })
      },
      setDay(date,isDate){
          const item = this.workList[this.$moment(date).format('YYYY-MM-DD')] || {}
          this.axios({
              method: "post",
              url: "/dms/calendar/board/save_work_date",
              data: {
                  maintainWorkDateList:[
                      {
                          date:this.$moment(date).format('YYYY-MM-DD'),
                          orgId:this.searchParams.orgId,
                          isWorkDate:isDate,
                          id:item.id
                      }
                  ]
              },
          }).then((res) => {
              if (res.code === 200) {
                  this.toggleAllPop('a')
                  this.$Message.success(res.msg);
                    this.serachClick()
              } else {
                  this.$Message.warning({
                      content: res.msg,
                      duration: 6,
                      closable: true,
                  });
              }
          })
      },
      toggleAllPop(date){
        const els = document.getElementsByClassName('oncontextmenuPop');
        for (let i=0;i<els.length;i++){
            if (els[i].getAttribute('data-date') === date){
                els[i].style.display = 'inline-block'
            }else{
                els[i].style.display = 'none'
            }
        }
      },
      onmousedown(e,date){
          e.preventDefault();
          if(e.button ==2){
                setTimeout(()=>{
                    this.toggleAllPop(date)
                },300)
          }
      },
    chongClick(){
      this.deviceMIdList = []
      this.orgCode = []
      this.searchParams = {}
      this.$store.commit('detail/SET_CALEND','')
      this.serachClick()
    },
    debounceSerach(fn, delay){
      let _this = this
      return function f(...args) {
        if (_this.timeID) {
          clearTimeout(_this.timeID);
        }
        _this.timeID = setTimeout(() => {
          fn(args);
        }, delay);
      };
    },
    clearChange(){
      this.$store.commit('detail/SET_CALEND','')
    },
    handleChangeWl(val) {
      const obj = this.deviceMIdList.find(item=> item.deviceMId === val.value)
      this.$store.commit('detail/SET_CALEND',obj.deviceMId)
    },
    handleRemote(query) {
      if (!query){
        return
      }
      const fn = this.debounceSerach(()=>{
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: _query,
            deviceNo: '',
            assetsNo:"",
            orgCode:this.searchParams.orgCode || '',
          },
        }).then((res) => {
          if (res.code === 200) {
            this.deviceMIdList = res.data.map(item=> {
              item.desc = item.deviceMId + '-' + item.deviceName + '-' + item.deviceNo
              return item;
            })
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        })
      },300)
      fn()
    },
    serachClick(){
      if (this.activType === 'year'){
        this.getMaintenanceYear()
      }
      if (this.activType === 'month'){
        this.getMaintenanceMonth()
      }
    },
    monthitemClick(){
      this.onTypeChange('month')
      this.getMaintenanceMonth()
    },
    dayitemClick(item){
      if (item.split('@')[2] == -1){
        return;
      }
      if (Number(item.split('@')[0]) === 0){
        this.$Message.warning('该任务还未生成,无法查看详情!')
        return
      }
      const row ={
        status:4,
        taskId:item.split('@')[0]
      }
      this.$store.commit('detail/SET_DATING',row)
      this.$router.push({
        path:'/maintenanceDetail'
      })
    },
    getListData(value,str) {
      let monthList = []
      let dataList = []
      const year = new Date(value).getFullYear()
      const month = new Date(value).getMonth() + 1
      const day = new Date(value).getDate()
      if (str === 'day'){
        this.dayList.forEach(val=>{
          if (val.year === year && val.month === month && val.day === day){
            if (val.contents && val.contents.length){
                 dataList = val.contents
            }
          }
        })
        return dataList
      }
      if (str === 'month'){
        this.monthList.forEach(val=>{
          if (val.year === year && val.month === month){
            if (val.contents && val.contents.length){
               monthList = monthList.concat(val.contents)
            }
          }
        })
        return monthList
      }
    },
    async getMaintenanceYear(){
      this.monthList= []
      // if (!this.searchParams.deviceMId){
      //   return
      // }
      const params ={
        year:this.dateInfo.slice(0,this.dateInfo.indexOf('年')),
        orgCode:this.searchParams.orgCode,
        deviceName:this.searchParams.deviceMId,
        itemLevel:this.searchParams.itemLevel,
      }
      const {data} = await getMaintenanceYear(params)
      this.monthList = data
    },
    async getMaintenanceMonth(){
          this.workList = []
          this.getWorkDay()
      this.dayList = []
      // if (!this.searchParams.deviceMId){
      //   return
      // }
      const year = this.dateInfo.slice(0,this.dateInfo.indexOf('年'))
      const month = parseInt(this.dateInfo.slice(this.dateInfo.indexOf('年') + 1,this.dateInfo.indexOf('月')))
      const params ={
        year,
        month,
        orgCode:this.searchParams.orgCode,
        deviceName:this.searchParams.deviceMId,
        itemLevel:this.searchParams.itemLevel
      }
      const {data} = await getMaintenanceMonth(params)
      this.dayList = data
    },
    dateSelect(date){
      if (this.activType === 'year'){
        this.dateInfo = moment(date).format("YYYY年MM月DD日")
        this.onTypeChange('month')
        this.getMaintenanceMonth()
      }
    },
    dateChange(date){
      // this.yearMonthstaus = false
      this.dateInfo = moment(date).format("YYYY年MM月DD日")
    },
    panelChange(date,mode){
      this.modeType = mode
      // if (this.activType === 'year' && mode === 'year' && !this.yearMonthstaus){
      //      this.onTypeChange('month')
      // }
    },
    todayClick(){
      this.calendarValue = moment(new Date())
      if (this.modeType === 'year'){
        this.onTypeChange('month')
      }
      this.$nextTick(()=>{
        this.dateInfo = moment(new Date()).format("YYYY年MM月DD日")
        this.getMaintenanceMonth()
      })
    },
    headerRender({ value, type, onChange, onTypeChange }) {
      let _this = this
      this.onTypeChange = onTypeChange
      this.activType = type
      const start = 0;
      const end = 12;
      const monthOptions = [];

      const current = value.clone();
      const localeData = value.localeData();
      const months = [];
      for (let i = 0; i < 12; i++) {
        current.month(i);
        months.push(localeData.monthsShort(current));
      }
      for (let index = start; index < end; index++) {
        monthOptions.push(
            <a-select-option class="month-item" key={`${index}`}>
              {months[index]}
            </a-select-option>,
        );
      }
      const month = value.month();

      const year = value.year();
      const options = [];
      for (let i = new Date().getFullYear(); i < year + 10; i += 1) {
        options.push(
            <a-select-option key={i} value={i} class="year-item">
              {i}{_this.$t('年')}
            </a-select-option>,
        );
      }
      return (
          <div style={{ padding: '10px',display:'flex',
            justifyContent:"space-between",alignItems:'center'}}>
            <span  style={{ fontSize: '17px',fontWeight: 'bold'}}>{_this.dateInfo}</span>
            <a-row type="flex" justify="end">
              <a-space>
                <Button type="info" onClick={_this.todayClick}>{_this.$t('今天')}</Button>
                <a-col>
                  <a-radio-group onChange={e => {
                    onTypeChange(e.target.value)
                    if (e.target.value === 'year'){
                      _this.getMaintenanceYear()
                    }
                    if (e.target.value === 'month'){
                      _this.getMaintenanceMonth()
                    }
                  }} value={type}>
                    <a-radio-button value="month">{_this.$t('月')}</a-radio-button>
                    <a-radio-button value="year">{_this.$t('年')}</a-radio-button>
                  </a-radio-group>
              </a-col>
              <a-col>
                <a-select
                    style={{ width: '120px' }}
                    dropdownMatchSelectWidth={false}
                    class="my-year-select"
                    onChange={newYear => {
                      // _this.yearMonthstaus = true
                      const now = value.clone().year(newYear);
                      onChange(now);
                      if (type === 'year'){
                        _this.getMaintenanceYear()
                      }
                      if (type === 'month'){
                        _this.getMaintenanceMonth()
                      }
                    }}
                    value={String(year)}
                >
                  {options}
                </a-select>
              </a-col>
                {
                  type === 'month' &&
                  <a-col>
                    <a-select
                        style={{ width: '120px' }}
                        dropdownMatchSelectWidth={false}
                        value={String(month)}
                        onChange={selectedMonth => {
                          // _this.yearMonthstaus = true
                          const newValue = value.clone();
                          newValue.month(parseInt(selectedMonth, 10));
                          onChange(newValue);
                          if (type === 'year'){
                            _this.getMaintenanceYear()
                          }
                          if (type === 'month'){
                            _this.getMaintenanceMonth()
                          }
                        }}
                    >
                      {monthOptions}
                    </a-select>
                  </a-col>
                }
                </a-space>
            </a-row>
          </div>
      );
    },
    handleCasChange(val,item) {
      this.searchParams.orgId = item[item.length - 1].id
      this.searchParams.orgCode = val[val.length - 1];
    },
    getOrgList() {
      let params = {
        level: 3
      }
      findOrgByToken(params).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.oncontextmenuPop{
    position: absolute;
    right: 10px;
    top: 35px;
    z-index: 11;
    background: #FFFFFF;
    box-shadow: 0px 4px 8px 0px rgba(0, 20, 45, 0.2);
    border-radius: 8px;
    padding: 8px 16px;
    display: none;
    transition: all linear;
}
.rightBtns{
    position: absolute;
    right: 3px;
    top: 3px;
    z-index: 11;
    .oncontextmenu{
        //background: #2d8cf0;
        padding: 3px 5px;
        font-size: 18px;
        //color: #fff;
        //border-radius: 5px;
    }
}
.list-layout{
  .tableContentBox{
    /deep/ .dayBox{

     .dayBox_item{
         cursor: pointer;margin: 5px 0;


     }
    }
    /deep/.ant-fullcalendar-fullscreen{
      .ant-fullcalendar-header{
        padding-top: 0;
      }
      .ant-fullcalendar-today{
        .ant-fullcalendar-date{
          background: #e6f7ff;
          .ant-fullcalendar-value{
            color: #1890ff;
          }
        }
      }
      .ant-fullcalendar table{
        .ant-fullcalendar-value{
          text-align: left;
        }
        thead tr th {
          border: 2px solid #d9d9d9;
          padding: 5px 12px;
          text-align: left;
        }
        tbody tr td{  border: 1px solid #d9d9d9; }
        .ant-fullcalendar td{ border: 1px solid #d9d9d9;}
        .ant-fullcalendar-date,.ant-fullcalendar-month{
          margin: 3px;
          border-top: none !important;
        }
      }
    }
  }
}
</style>
